use crate::data_structure::list_node::ListNode;

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode {
            next: None,
            val,
        }
    }

    pub fn vec1d_to_list_node(vec: Vec<i32>) -> Option<Box<ListNode>> {
        let mut head = None;
        let mut tail = &mut head;

        for num in vec.iter() {
            *tail = Some(Box::new(ListNode::new(*num)));
            tail = &mut tail.as_mut().unwrap().next;
        }

        head
    }

    pub fn list_node_to_vec1d(list_node: Option<Box<ListNode>>) -> Vec<i32> {
        let mut vec = Vec::new();
        let mut current = list_node;

        while let Some(node) = current {
            vec.push(node.val);
            current = node.next;
        }

        vec
    }

    pub fn list_node_to_string(list_node: Option<Box<ListNode>>) -> String {
        let mut string = String::new();
        let mut current = list_node;

        while let Some(node) = current {
            string.push_str(&node.val.to_string());
            string.push_str(" -> ");
            current = node.next;
        }

        string.push_str("None");

        string
    }

}

#[cfg(test)]
mod tests {
    // 这两个至少引入一个！
    // use super::*;
    use crate::data_structure::list_node::ListNode;

    #[test]
    fn test_vec1d_to_list_node() {
        let vec = vec![1, 2, 3, 4, 5];
        let list_node = ListNode::vec1d_to_list_node(vec);

        println!("{:?}", list_node);
    }

    #[test]
    fn test_list_node_to_vec1d() {
        let mut list_node = Some(Box::new(ListNode::new(1)));
        list_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(2)));
        list_node.as_mut().unwrap().next.as_mut().unwrap().next = Some(Box::new(ListNode::new(3)));

        let vec = ListNode::list_node_to_vec1d(list_node);

        println!("{:?}", vec);
    }

    #[test]
    fn test_list_node_to_string() {
        let mut list_node = Some(Box::new(ListNode::new(1)));
        list_node.as_mut().unwrap().next = Some(Box::new(ListNode::new(2)));
        list_node.as_mut().unwrap().next.as_mut().unwrap().next = Some(Box::new(ListNode::new(3)));

        let string = ListNode::list_node_to_string(list_node);
        // 1 -> 2 -> 3 -> None
        println!("{}", string);
    }
}